import { Button, DatePicker, Form, Select, message } from "antd";
import "./statistics.css";
// import * as echarts from "echarts";
import { useEffect, useMemo, useRef, useState } from "react";
import {
  meetingRoomUsedCount,
  userBookingCount,
} from "../../interfaces/interfaces";
import dayjs from "dayjs";
import { useForm } from "antd/es/form/Form";

// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
// 引入柱状图图表，图表后缀都为 Chart
import { BarChart,PieChart } from 'echarts/charts';
// 引入标题，提示框，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components';
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  PieChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

interface UserBookingData {
  userId: string;
  username: string;
  bookingCount: string;
}
interface MeetingRoomUsedData {
  meetingRoomName: string;
  meetingRoomId: number;
  usedCount: string;
}

export function Statistics() {
  const [userBookingData, setUserBookingData] =
    useState<Array<UserBookingData>>();
  const [meetingRoomUsedData, setMeetingRoomUsedData] =
    useState<Array<MeetingRoomUsedData>>();

  const [form] = useForm();
  const isBar = useMemo(
    ()=> form.getFieldValue("chartType") === "bar",
  [form.getFieldValue("chartType")]);
  
  const containerRef = useRef<HTMLDivElement>(null);
  const containerRef2 = useRef<HTMLDivElement>(null);

  async function getStatisticData(values: {
    startTime: string;
    endTime: string;
  }) {
    const startTime = dayjs(values.startTime).format("YYYY-MM-DD");
    const endTime = dayjs(values.endTime).format("YYYY-MM-DD");

    const res = await userBookingCount(startTime, endTime);

    const { data } = res.data;
    if (res.status === 201 || res.status === 200) {
      setUserBookingData(data);
    } else {
      message.error(data || "系统繁忙，请稍后再试");
    }

    const res2 = await meetingRoomUsedCount(startTime, endTime);

    const { data: data2 } = res2.data;
    if (res2.status === 201 || res2.status === 200) {
      setMeetingRoomUsedData(data2);
    } else {
      message.error(data2 || "系统繁忙，请稍后再试");
    }
  }
  
  useEffect(() => {
    const myChart = echarts.init(containerRef.current);
    if (!userBookingData) {
      return;
    }
    const option = {
      title: {
        text: "用户预定情况",
      },
      tooltip: {},
      ...isBar&&{
      xAxis: {
        data: userBookingData?.map(item => item.username),
      },
      yAxis: {}},
      series: [
        {
          name: "预定次数",
          type: form.getFieldValue("chartType"),
          data: userBookingData?.map(item => {
            return {
              name: item.username,
              value: item.bookingCount,
            };
          }),
        },
      ],
    }
    myChart.setOption(option);
    return ()=>{
      myChart.dispose()
    }
  }, [userBookingData]);

  useEffect(() => {
    const myChart = echarts.init(containerRef2.current);

    if (!meetingRoomUsedData) {
      return;
    }
    const option = {
      title: {
        text: "会议室使用情况",
      },
      tooltip: {},
      ...isBar&& {
      xAxis: {
        data: userBookingData?.map(item => item.username),
      },
      yAxis: {}},
      series: [
        {
          name: "使用次数",
          type: form.getFieldValue("chartType"),
          data: meetingRoomUsedData?.map(item => {
            return {
              name: item.meetingRoomName,
              value: item.usedCount,
            };
          }),
        },
      ],
    }
    myChart.setOption(option);
    return ()=>{
      myChart.dispose()
    }
  }, [meetingRoomUsedData]);

  return (
    <div id="statistics-container">
      <div className="statistics-form">
        <Form
          form={form}
          onFinish={getStatisticData}
          name="search"
          layout="inline"
          colon={false}
        >
          <Form.Item label="开始日期" name="startTime">
            <DatePicker />
          </Form.Item>

          <Form.Item label="结束日期" name="endTime">
            <DatePicker />
          </Form.Item>

          <Form.Item label="图表类型" name="chartType" initialValue={"pie"}>
            <Select>
              <Select.Option value="pie">饼图</Select.Option>
              <Select.Option value="bar">柱形图</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className="statistics-chart" ref={containerRef}></div>
      <div className="statistics-chart" ref={containerRef2}></div>
    </div>
  );
}

export default Statistics;